package com.autumn.mybatis.context;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import com.autumn.mybatis.mapper.AutumnMybatisClassPathMapperScanner;
import com.autumn.mybatis.provider.IDbProvider;
import com.autumn.spring.boot.bean.AbstractImportBeanDefinitionRegister;
import com.autumn.spring.boot.bean.BeanDefinitionRegisterManager;
import com.autumn.util.tuple.TupleTwo;

/**
 * 扫描多数据源注册
 * 
 * @author 老码农
 *
 *         2017-11-30 12:22:50
 */
public class AutumnMybatisMultipleDataSourceDefinitionRegister extends AbstractImportBeanDefinitionRegister
		implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {

	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		List<DefinitionRegistrarInfo> regInfos = DefinitionRegistrarUtils
				.multipleDataSourceMapperScannerRegistrarInfos(this.getEnvironment(), importingClassMetadata);

		BeanDefinitionRegisterManager regManager = new BeanDefinitionRegisterManager(this.getEnvironment(),
				this.getResourceLoader(), registry);

		List<MultipleDefinitionRegistrarInfo> multipleInfos = new ArrayList<>();
		for (DefinitionRegistrarInfo regInfo : regInfos) {
			TupleTwo<String, Class<? extends IDbProvider>> tupleTwo = DefinitionRegistrarUtils
					.registerDbProvider(regManager, regInfo);
			multipleInfos.add(new MultipleDefinitionRegistrarInfo(regInfo, tupleTwo));
		}
		DefinitionRegistrarUtils.registerMultipleDataSource(regManager, multipleInfos);
		for (DefinitionRegistrarInfo regInfo : regInfos) {
			AutumnMybatisClassPathMapperScanner scanner = new AutumnMybatisClassPathMapperScanner(registry);
			if (this.getResourceLoader() != null) {
				scanner.setResourceLoader(this.getResourceLoader());
			}
			scanner.setMapperRegisterBeanName(regInfo.getMapperRegisterBeanName());
			scanner.setSqlSessionFactoryBeanName(regInfo.getSqlSessionFactoryBeanName());
			scanner.setSqlSessionTemplateBeanName(regInfo.getSqlSessionTemplateBeanName());
			scanner.registerFilters();
			scanner.doScan(regInfo.getMapperInterfacePackages());
		}
	}
}
